package tjuscs.ourmap;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.R.color;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.graphics.Paint;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import baidumapsdk.demo.R;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.BDNotifyListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKEvent;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.MapView.LayoutParams;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;

/**
 * 在一个圆周上添加自定义overlay.
 */
public class DisplayMap extends Activity {

	final static String TAG = "MainActivty";
	public static final String strKey = "8A9C6B23DAAB5712A9382556E1CBB690F008B5E3";
	static MyMapView mMapView = null;
	BMapManager mBMapManager = null;
	public MKMapViewListener mMapListener = null;
	FrameLayout mMapViewContainer = null;

	Button friend = null;
//	Button group = null;
	Spinner spinner = null;
	Button setpoint = null;
	ImageButton more = null;

	Button updateButton = null;

	Button chosedisplayButton = null;
	Button diaplayallButton = null;

	EditText indexText = null;
	int index = 0;
	
	boolean needSetPoint = true;

	public MyLocationOverlay myLocationOverlay = null;
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	public NotifyLister mNotifyer = null;
	LocationData locData = null;

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Toast.makeText(getApplicationContext(), "msg:" + msg.what,
					Toast.LENGTH_SHORT).show();
		};
	};

	GeoPoint pt;
	/**
	 * 圆心经纬度坐标
	 */
	static double cLat = 39909230;
	static double cLon = 116397428;
	// 存放overlayitem
	public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	// 存放overlay图片
	public List<Drawable> res = new ArrayList<Drawable>();
	// 获取队友的位置信息
	public List<GeoPoint> geos = new ArrayList<GeoPoint>();

	// 获取队友的信息
	public List<String> names = new ArrayList<String>();

	public List<Integer> mSelectedItems = new ArrayList<Integer>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_itemizedoverlay);
		
		mMapView = (MyMapView)findViewById(R.id.bmapView);
		mBMapManager = new BMapManager(getApplicationContext());
		mBMapManager.init(strKey, new MyGeneralListener());
		initMapView();

		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
	//	option.setScanSpan(5000);
		mLocClient.setLocOption(option);
		mLocClient.start();
		mMapView.getController().setZoom(19);
		mMapView.getController().enableClick(true);
		// 各个Button的监听器
		friend = (Button) findViewById(R.id.friend);
		 spinner = (Spinner)findViewById(R.id.groupSpinner);
//		group = (Button) findViewById(R.id.mygroup);
		setpoint = (Button) findViewById(R.id.setpoint);
		more = (ImageButton) findViewById(R.id.more);

		updateButton = (Button) findViewById(R.id.updateButton);
		
		updateButton.setOnClickListener(new updateButtonClickListener());
		friend.setOnClickListener(new friendClickListener());
		groupClick();
	//	group.setOnClickListener(new groupClickListener());
		more.setOnClickListener(new moreClickListener());
		setpoint.setOnClickListener(new setPointClickListener());
		mMapListener = new MKMapViewListener() {
			@Override
			public void onMapMoveFinish() {
				// TODO Auto-generated method stub
				Log.d("hjtest", "hjtest" + "onMapMoveFinish");
				/**/
			}
						

			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				// TODO Auto-generated method stub
				String title = "";
				if (mapPoiInfo != null) {
					title = mapPoiInfo.strText;
					
					Toast.makeText(DisplayMap.this, title,
							Toast.LENGTH_SHORT).show();

					
				}

			}

			@Override
			public void onGetCurrentMap(Bitmap b) {
				// TODO Auto-generated method stub
				Log.d("hjtest", "hjtest" + "getmap OK");
			}

			@Override
			public void onMapAnimationFinish() {
				// TODO Auto-generated method stub
				Log.d("hjtest", "hjtest" + "onMapAnimationFinish");

			}
		};
		mMapView.regMapViewListener(mBMapManager, mMapListener);
		mMapView.setOnClickListener(new myMapViewClickListener());

		myLocationOverlay = new MyLocationOverlay(mMapView);
		locData = new LocationData();
		myLocationOverlay.setData(locData);
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		mMapView.refresh();

		
	}

	// 从服务器获取数据接口
	// ************************************************************************************************

	public int getNumOfTeam() {
		// 获得队员人数
		int size = 6;
		return size;
	}

	// 从获取队员位置信息
	public void getGeosInfo() {
		int iSize = getNumOfTeam();
		double pi = 3.1415926;
		// overlay半径
		int r = 1000;
		// 准备overlay 数据
		for (int i = 0; i < iSize; i++) {
			int lat = (int) (cLat + r * Math.cos(2 * i * pi / iSize));
			int lon = (int) (cLon + r * Math.sin(2 * i * pi / iSize));
			geos.add(new GeoPoint(lat, lon));
			Log.d("hjtest", "cLat: geo" + cLat);
			Log.d("hjtest", "cLon: geo " + cLon);
		}
	}

	// 准备overlay和数据，该overlay数据用来在地图上显示。
	public void initOverlay() {
		for (int i = 0; i < getNumOfTeam(); i++) {
			OverlayItem item = new OverlayItem(geos.get(i), "item" + i, "item"
					+ i);
			item.setMarker(res.get(i % (res.size())));
			mGeoList.add(item);
		}
	}

	// 需要连接服务器
	public void GetStrs() {
		
		names.add("宇");
		names.add("磊");
		names.add("阳");
		names.add("慧");
		names.add("琳");
		names.add("苑");		
		
	}

	public void initDrawableList() {
		GetStrs();
		for (int i = 0; i < getNumOfTeam(); i++) {
			Log.d(TAG,"theTeamNum = "+getNumOfTeam());
			Log.d(TAG,"names 【i】 = " + names.get(i));
			
			res.add(processBitmap(names.get(i)));
		}

	}

	// ****************************************************************************************************

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onDestroy() {
		mMapView.destroy();

		if (mBMapManager != null) {
			mBMapManager.destroy();
			mBMapManager = null;
		}
		super.onDestroy();
	}

	private void initMapView() {
		mMapView.setLongClickable(true);
		// mMapView.getController().setZoom(14);
		// mMapView.getController().enableClick(true);
		// mMapView.setBuiltInZoomControls(true);

	}

	public void testItemClick() {

		initDrawableList();
		getGeosInfo();
		initOverlay();

		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.friend_menu,
				(ViewGroup) findViewById(R.id.friendMenu));

		final Dialog dialog = new AlertDialog.Builder(this).setView(layout)
				.show();

		chosedisplayButton = (Button) layout.findViewById(R.id.chosedisplay);
		diaplayallButton = (Button) layout.findViewById(R.id.diaplayall);

		chosedisplayButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				choseFriend();
			}
		});

		diaplayallButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
				for (int i = 0; i < getNumOfTeam(); i++) {
					mSelectedItems.add(i);
				}
				DisplayFriend(mSelectedItems);
			}
		});

	}

	public void choseFriend() {
		mSelectedItems.clear();
		String[] items = new String[getNumOfTeam()];
		for (int i = 0; i < getNumOfTeam(); i++) {
			items[i] = names.get(i);
		}
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("请选择要关注的好友");
		builder.setMultiChoiceItems(items, null,
				new DialogInterface.OnMultiChoiceClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which,
							boolean isChecked) {
						if (isChecked) {
							// If the user checked the item, add it to the
							// selected items
							mSelectedItems.add(which);
						} else if (mSelectedItems.contains(which)) {
							// Else, if the item is already in the array, remove
							// it
							mSelectedItems.remove(Integer.valueOf(which));
						}
					}
				});
		builder.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

		builder.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						DisplayFriend(mSelectedItems);
					}

				});
		builder.show();

	}

	public void DisplayFriend(List<Integer> mSelectedItems) {
		Drawable marker = DisplayMap.this.getResources().getDrawable(
				R.drawable.icon_marka);
		OverlayTest ov = new OverlayTest(marker, this);

		for (int i = 0; i < mSelectedItems.size(); i++) {
			ov.addItem(mGeoList.get(mSelectedItems.get(i)));
		}
		mMapView.getOverlays().clear();
		mMapView.getOverlays().add(myLocationOverlay);
		mMapView.getOverlays().add(ov);
		mMapView.refresh();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	static class OverlayTest extends ItemizedOverlay<OverlayItem> {
		public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
		private Context mContext = null;
		static PopupOverlay pop = null;
		private Button mBtn = null;
		Toast mToast = null;

		public OverlayTest(Drawable marker, Context context) {
			super(marker);
			this.mContext = context;
			pop = new PopupOverlay(DisplayMap.mMapView,
					new PopupClickListener() {

						@Override
						public void onClickedPopup(int index) {
							if (null == mToast)
								mToast = Toast
										.makeText(mContext, "popup item :"
												+ index + " is clicked.",
												Toast.LENGTH_SHORT);
							else
								mToast.setText("popup item :" + index
										+ " is clicked.");
							mToast.show();
						}
					});
			populate();

		}

		protected boolean onTap(int index) {

			Bitmap[] bmps = new Bitmap[3];
			if (index % 3 == 0) {
				try {
					bmps[0] = BitmapFactory.decodeStream(mContext.getAssets()
							.open("marker1.png"));
					bmps[1] = BitmapFactory.decodeStream(mContext.getAssets()
							.open("marker2.png"));
					// bmps[2] = BitmapFactory.decodeStream(mContext.getAssets()
					// .open("marker3.png"));
					bmps[2] = BitmapFactory.decodeStream(mContext.getAssets()
							.open("marker4.png"));
				} catch (IOException e) {
					e.printStackTrace();
				}
				pop.showPopup(bmps, mGeoList.get(index).getPoint(), 32);
			} else if (index % 3 == 1) {
				try {
					bmps[2] = BitmapFactory.decodeStream(mContext.getAssets()
							.open("marker4.png"));
					// bmps[2] = BitmapFactory.decodeStream(mContext.getAssets()
					// .open("marker1.png"));
					bmps[1] = BitmapFactory.decodeStream(mContext.getAssets()
							.open("marker2.png"));
					bmps[0] = BitmapFactory.decodeStream(mContext.getAssets()
							.open("marker3.png"));
				} catch (IOException e) {
					e.printStackTrace();
				}
				pop.showPopup(bmps, mGeoList.get(index).getPoint(), 32);
			} else {
				if (mBtn == null)
					mBtn = new Button(mContext);
				mBtn.setText("TestTest");
				mMapView.addView(mBtn, new MapView.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
						mGeoList.get(index).getPoint(),
						MapView.LayoutParams.BOTTOM_CENTER));
			}

			if (null == mToast)
				mToast = Toast.makeText(mContext, mGeoList.get(index)
						.getTitle(), Toast.LENGTH_SHORT);
			else
				mToast.setText(mGeoList.get(index).getTitle());
			mToast.show();

			return true;
		}

		public boolean onTap(GeoPoint pt, MapView mapView) {
			if (pop != null) {
				pop.hidePop();
				if (mBtn != null) {
					mMapView.removeView(mBtn);
					mBtn = null;
				}
			}
			super.onTap(pt, mapView);
			return false;
		}

		@Override
		protected OverlayItem createItem(int i) {
			return mGeoList.get(i);
		}

		@Override
		public int size() {
			return mGeoList.size();
		}

		public void addItem(OverlayItem item) {
			mGeoList.add(item);
			populate();
		}

		public void removeItem(int index) {
			mGeoList.remove(index);
			populate();
		}

	}

	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	private class MyGeneralListener implements MKGeneralListener {

		@Override
		public void onGetNetworkState(int iError) {
			if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
				Toast.makeText(getApplicationContext(), "您的网络出错啦！",
						Toast.LENGTH_LONG).show();
			} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
				Toast.makeText(getApplicationContext(), "输入正确的检索条件！",
						Toast.LENGTH_LONG).show();
			}
			// ...
		}

		@Override
		public void onGetPermissionState(int iError) {

		}
	}

	/**
	 * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
	 */
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			locData.latitude = location.getLatitude();
			locData.longitude = location.getLongitude();
			locData.accuracy = location.getRadius();
			locData.direction = location.getDerect();
			myLocationOverlay.setData(locData);
			mMapView.refresh();
			mMapView.getController().animateTo(
					new GeoPoint((int) (locData.latitude * 1e6),
							(int) (locData.longitude * 1e6)),
					mHandler.obtainMessage(1));
			cLat = locData.latitude * 1e6;
			cLon = locData.longitude * 1e6;
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

	public class NotifyLister extends BDNotifyListener {
		public void onNotify(BDLocation mlocation, float distance) {
		}
	}

	// 处理图片
	private BitmapDrawable processBitmap(String str) {
		Resources re = getResources();
		InputStream is = re.openRawResource(R.drawable.bg_fri_box);
		Bitmap bmp = BitmapFactory.decodeStream(is);
		int w = bmp.getWidth();
		int h = bmp.getHeight();
		Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
		Canvas canvas = new Canvas(newb);
		canvas.drawBitmap(bmp, 0, 0, null);// 在 0，0坐标开始画入src
		Paint mPaint = new Paint();
		mPaint.setTextSize(30);
		mPaint.setColor(Color.RED);
		mPaint.setTypeface(Typeface.DEFAULT_BOLD);

		mPaint.setTextAlign(Paint.Align.CENTER);
		canvas.drawText(str, w / 2, h / 2, mPaint);
		canvas.save(Canvas.ALL_SAVE_FLAG);
		canvas.restore();

		BitmapDrawable bd = new BitmapDrawable(getResources(), newb);
		return bd;
	}
	
	class updateButtonClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			mLocClient.requestLocation();
		}
		
	}
	
	class friendClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			testItemClick();
		}
		
	}
	
	
	private void groupClick() {		
		
        //准备一个数组适配器
        ArrayAdapter adapter = ArrayAdapter.createFromResource(
                this, R.array.qunzus, android.R.layout.simple_spinner_item);
        //设置下拉样式  android里面给大家提供了丰富的样式和功能图片
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //为下拉列表设置适配器
        spinner.setAdapter(adapter);
  
        //定义子元素选择监听器
        OnItemSelectedListener oisl=  new OnItemSelectedListener() {
  
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                  Toast.makeText(DisplayMap.this,"选择的群组： " +
                  parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
            }
  
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        };
        spinner.setVisibility(View.VISIBLE);  
        //为下拉列表绑定事件监听器
        spinner.setOnItemSelectedListener(oisl);
    }
		
	
	
	class moreClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
		}
		
	}
	
	class setPointClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			needSetPoint = false;
		}
		
	}
	
	class myMapViewClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			if(needSetPoint)return;
			
			PopupOverlay pop = new PopupOverlay(mMapView,
					new PopupClickListener() {

						@Override
						public void onClickedPopup(int index) {
							// TODO Auto-generated method stub 
							needSetPoint = true;	
							mMapView.refresh();
							
							//添加标志集结点的overlay
							disPlaySetPoint();
						}
					});
			Bitmap[] bmps = new Bitmap[1];
			try {
				bmps[0] = BitmapFactory.decodeStream(getAssets().open(
						"marker.png"));
				
			} catch (IOException e) {
				e.printStackTrace();
			}			
		
			// 弹出pop,隐藏pop
			pop.showPopup(bmps, mMapView.pt, 32);
		
		}
		
	}
	
	public void disPlaySetPoint(){
		Drawable marker = DisplayMap.this.getResources().getDrawable(R.drawable.icon_marka);
	    mMapView.getOverlays().clear();
	    OverlayTest ov = new OverlayTest(marker, this);
		OverlayItem item= new OverlayItem(mMapView.pt,null,null);
	    ov.addItem(item);
	    
	    mMapView.getOverlays().add(ov);
	    mMapView.refresh();
	 //   mMapView.getController().setCenter(new GeoPoint(cLat,cLon));
	}
}
